package com.monkeyboy.demo.transaction;

import org.apache.commons.lang3.StringUtils;
import org.apache.rocketmq.client.producer.*;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.common.message.MessageExt;

import java.util.concurrent.*;

/**
 * 事务消息
 */
public class Producer {

    public static void main(String[] args) throws Exception {
        //1.创建消息生产者producer，并制定生产者组名
        TransactionMQProducer producer = new TransactionMQProducer("group5");
        //2.指定Nameserver地址
        producer.setNamesrvAddr("192.168.1.140:9876;192.168.1.141:9876");
        ExecutorService executorService = new ThreadPoolExecutor(2, 5, 100, TimeUnit.SECONDS, new ArrayBlockingQueue<>(2000),
                new ThreadFactory() {
                    @Override
                    public Thread newThread(Runnable r) {
                        Thread thread = new Thread(r);
                        thread.setName("group5" + "-thread");//重新为线程池里面的线程取一个名字
                        return thread;
                    }
                });
        producer.setExecutorService(executorService);
        //添加事务监听器，这个监听器主要做两件事，1：执行异步的本地事务，2：如果消息投递失败后会进行回查
        producer.setTransactionListener(new TransactionListener() {
            /**
             * 在该方法中执行本地事务
             * @param msg
             * @param arg
             * @return
             */
            @Override
            public LocalTransactionState executeLocalTransaction(Message msg, Object arg) {
                //回调的参数
                String callArg = (String) arg;
                System.out.println(callArg);
                if (StringUtils.equals("TAGA", msg.getTags())) {
                    return LocalTransactionState.COMMIT_MESSAGE;//提交事务
                } else if (StringUtils.equals("TAGB", msg.getTags())) {
                    return LocalTransactionState.ROLLBACK_MESSAGE;//回滚
                } else if (StringUtils.equals("TAGC", msg.getTags())) {
                    return LocalTransactionState.UNKNOW;//不做任何处理，会进行回查，会进入下面的回查方法里面
                }
                //tx.commit
                //LocalTransactionState.ROLLBACK_MESSAGE;//rocketmq会废弃当前的消息
                return LocalTransactionState.UNKNOW;//UNKNOW会让rocketmq定期的进行回查，回查就是调用下面的方法
            }

            /**
             * 该方法时MQ进行消息事务状态回查，相当于是一个消息的补偿
             * 解决一些commit超时的情况
             * 自己的想法是如果处理失败了就存入到数据库里面
             * @param msg
             * @return
             */
            @Override
            public LocalTransactionState checkLocalTransaction(MessageExt msg) {
                System.out.println("回查消息的Tag:" + msg.getTags());
                return LocalTransactionState.COMMIT_MESSAGE;
            }
        });

        //3.启动producer
        producer.start();

        String[] tags = {"TAGA", "TAGB", "TAGC"};

        for (int i = 0; i < 3; i++) {
            //4.创建消息对象，指定主题Topic、Tag和消息体
            /**
             * 参数一：消息主题Topic
             * 参数二：消息Tag
             * 参数三：消息内容
             */
            Message msg = new Message("TransactionTopic", tags[i], ("Hello World" + i).getBytes());
            //5.发送消息，第二个参数可以指定topic,tag，回调的参数
            SendResult result = producer.sendMessageInTransaction(msg, "我是回调的参数");
            //发送状态
            SendStatus status = result.getSendStatus();

            System.out.println("发送结果:" + result);

            //线程睡1秒
            TimeUnit.SECONDS.sleep(2);
        }

        //6.关闭生产者producer
        //producer.shutdown();
    }
}
